package online.szlib.com.rest.controller;

import java.util.List;

import online.szlib.com.common.utils.JSONHelper;
import online.szlib.com.core.domain.User;
import online.szlib.com.core.services.UserService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

@Controller
@RequestMapping("/api/users")
public class UserRestController {

    private static Logger logger = LoggerFactory.getLogger(UserRestController.class);

    @Autowired
    private UserService userService;

	// Http Get All
	@RequestMapping(method = RequestMethod.GET)
	@ResponseBody
	public List<User> getAll() {
		System.out.println("List Users >>>>>>>>>>>>>>>>>>>>");
		return userService.listUsers();
	}
	
	// Http Get One
	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	@ResponseBody
	public User get(@PathVariable("id") Long id) {
		logger.debug("Get One User >>>>>>>>>>>>>>>>>>>>");
		return userService.getUser(id);
	}
    
	// Http Create One
	@RequestMapping(method = RequestMethod.POST, produces = "application/json")
	public ResponseEntity<User> createUser(@RequestBody User user) {
		logger.info("Create one User >>>>>>>>>>>>>>>>>>>>");
		userService.create(user);
		return new ResponseEntity<User>(user, JSONHelper.getJSONHeaders(), HttpStatus.CREATED);
	}
    
	// Http Update One User
	@RequestMapping(value = "/{id}", method = RequestMethod.PUT)
	@ResponseStatus(HttpStatus.OK)
	public void update(@RequestBody User entity, @PathVariable("id") Long id) {
		entity.setUserId(id);
		logger.info("Update one User >>>>>>>>>>>>>>>>>>>>");
		userService.update(entity);
	}
    
    // Http Delete One
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public ResponseEntity<Long> deleteUser(@PathVariable Long id) {
    	logger.debug("Delete One User >>>>>>>>>>>>>>>>>>>>");
		userService.deleteById(id);
        return new ResponseEntity<Long>(id, HttpStatus.OK);
    }

}
